from django import template
from django.utils.safestring import mark_safe

from settings import MEDIA_URL

from djips_common.models import Color

register = template.Library()

BASE_INDENT =  '  '

@register.filter(name='djips_filesystem')
def filesystem(folder, options):
    """ Renders a Folder element as an HTML tree.

    options is a dictionnary which should contains those keys:
    - url: the url for created links. Should contain a slot ('%s') to insert
      folder id.
    - current_folder: a folder that should be highlighted (the CSS class
      'current_folder' is applied to the <li> tag)
    - new_folder: a list of folders to highlight (the CSS class 'new_folder'
      is applied on the <li> tags).
    """

    def _make_link(folder, url, indent):
	html = '%(indent)s<a href="%(url)s">%(name)s</a>'

	try:
	    url %= folder.id
	except TypeError:
	    # There was no slot or too much. We keep the url as it.
	    pass
	    
	return html % {'indent': indent,
		       'url': url,
		       'name': folder.name }

    def _render_folder(folder, url = '', indent = '', sub_content = '', 
		     current_folder = None, new_folders = []):
	html = '%(indent)s<li class="%(classes)s">%(content)s%(subcontent)s</li>'

	sub_content = []
	for sub_folder in folder.sub_folders.all():
	    sub_content.append(_render_folder(sub_folder, url,
					      indent + BASE_INDENT*2,
					      '', current_folder, new_folders))
	if sub_content:
	    sub_html = '%(indent)s\n<ul class="djips_filesystem">' + \
		'%(sub_content)s\n%(indent)s</ul>'

	    sub_html %= {'indent': indent + BASE_INDENT,
			 'sub_content': '\n'.join(sub_content)}
	else:
	    sub_html = ''

	classes = ['djips_filesystem']
	if folder == current_folder:
	    classes.append('current_folder')

	if folder in new_folders:
	    classes.append('new_folder')

	return html % {'indent': indent,
		       'classes': '\n' .join(classes),
		       'content': _make_link(folder, url, indent),
		       'subcontent': sub_html}

    if folder:
	options['folder'] = folder
        wrapper = '<div class="djips_filesystem">' + \
	    '<ul class="djips_filesystem">\n%s</ul></div>'
	return mark_safe(wrapper % _render_folder(**options))

filesystem.is_safe = True

@register.filter(name='djips_plainfilesystem')
def plainfilesystem(folder, options):
    """ Basicaly the same filter than above, except that it does
    not produce nested lists, just a plain list.
    """

    def _make_link(url, folder, depth):
	try:
	    url %= folder.id
	except:
	    pass

	return '<a href="%(link)s">%(folder_name)s</a>' % \
	    {'link': url,
	     'folder_name': folder.name}

    def _render_leaf(url, folder, depth):
	return '<li class="djips_plainfilesystem">%(link)s</li>' % \
	    {'link': _make_link(url, folder, depth)}

    def _render_node(url='', folder=None, depth=0):
	html = _render_leaf(url, folder, depth)
	html += '\n'.join([_render_node(url, subf, depth +1)
			   for subf in folder.sub_folders.all()])

	return html

    if folder:
	options['folder'] = folder
        wrapper = '<ul class="djips_plainfilesystem">\n%s</ul>'
	return mark_safe(wrapper % _render_node(**options))

plainfilesystem.is_safe = True


@register.filter(name='djips_tags_to_options')
def tags_to_options(tags):
    
    result = ''

    def _render_tag(tag, prefix = ''):
        name = ''
        for attr in tag.attributes.all():
            if attr.lang.default:
                name = attr.name

        res = '<option name="%s" value="%s">%s %s</option>\n' % \
              (name, tag.id, prefix, name)
        for son in tag.son_tags.all():
            res += _render_tag(son, prefix + '-')

        return res
    
    for tag in tags:
        result += _render_tag(tag)

    return mark_safe(result)

tags_to_options.is_safe = True
            
@register.filter(name='djips_dynamic_key')
def dynamic_key(dict, key):
    if key in dict:
	return dict[key]

    return ''

@register.filter(name='djips_mark_options')
def mark_options(img_mark):
    options = []

    try:
	img_mark = int(img_mark)
    except ValueError:
	img_mark = 0
    
    for i in range(0, 6):
	if img_mark == i:
	    selected = 'selected="selected"'
	else:
	    selected = ''
		 
	options.append('<option value="%s" %s>%s</option>' % \
		       (i, selected, i or '-' ))

    return mark_safe('\n'.join(options))

mark_options.is_safe = True


@register.filter(name='djips_color_options')
def color_options(img_color):
    options = []
    colors = Color.objects.all()

    if not img_color:
	options.append('<option value="-" selected="selected">-</option>')
    else:
	options.append('<option value="-">-</option>')

    for color in colors:
	if not img_color:
	    selected = ''
	elif color.id == img_color.id:
	    selected = 'selected="selected"'
	else:
	    selected = ''

	options.append('<option value="%s" %s>%s</option>' % \
		       (color.id, selected, color.name))

    return mark_safe('\n'.join(options))

color_options.is_safe = True

@register.filter(name='djips_dia_stars')
def djips_dia_stars(image):
    """ Shows stars applied to an image.
    """
    html = ''
    for i in range(1, 6):
	if i > image.mark:
	    img = 'dia_spot_small.gif'
	else:
	    img = 'dia_spot_big.gif'

	    
	html += ('<img src="%s/djips/images/%s" />' % (MEDIA_URL, img))
    return mark_safe(html)

djips_dia_stars.is_safe = True

@register.filter(name='djips_mark_chooser')
def djips_mark_chooser(mark):
    """ Pretty close to djips_dia_stars, except for images
    rendered and Ajax capabilities.
    """
    html = ('<div class="mark_widget_container">'
	    '<input type="hidden" name="mark" value="%s">')
    html %= mark
    html += ('<img src="%s/djips/images/star_delete.gif" class="no_star" />' % 
	     MEDIA_URL)

    for i in range(1, 6):
	if i > mark:
	    img = 'star_unapplied.gif'
	else:
	    img = 'star_applied.gif'

	html += ('<img src="%s/djips/images/%s" class="mark_widget_%s" />' % 
		 (MEDIA_URL, img, i))

    html += '</div>'
    return mark_safe(html)
djips_mark_chooser.is_safe = True


@register.filter(name='djips_color_chooser')
def djips_color_chooser(color):
    if color:
	color_id = color.id
    else:
	color_id = -1

    html = ('<div class="color_widget_container">'
	    '<input type="hidden" name="color" value="%s" />' %
	    color_id)

    colors = Color.objects.all()

    for c in colors:
	html += ('<div style="background: #%s;"' 
		 'class="color_display %s" rel="color_widget_%s"'
		 'title="%s"></div>' %
		 (c.value,
		  color_id == c.id and 'current' or '',
		  c.id,
		  c.name))

    return mark_safe(html + '</div>')
djips_color_chooser.is_safe = True
